package org.jeecg.modules.santu.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeecg.dingtalk.api.user.vo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.MD5Util;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.activemq.Producer;
import org.jeecg.modules.demo.wechat.pojo.QueueMessage;
import org.jeecg.modules.santu.entity.TbGroup;
import org.jeecg.modules.santu.entity.TbGroupMember;
import org.jeecg.modules.santu.service.ITbGroupMemberService;
import org.jeecg.modules.santu.service.ITbGroupService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.util.RandImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

/**
* @Description: 群成员
* @Author: jeecg-boot
* @Date:   2025-02-24
* @Version: V1.0
*/
@Api(tags="群成员")
@RestController
@RequestMapping("/santu/tbGroupMember")
@Slf4j
public class TbGroupMemberController extends JeecgController<TbGroupMember, ITbGroupMemberService> {

   @Autowired
   private ITbGroupMemberService tbGroupMemberService;

    private static final String BASE_CHECK_CODES = "1234567890";

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private Producer producer;

    @Autowired
    private ITbGroupService tbGroupService;


    @GetMapping(value = "/test")
    public Result<?> test() {
        TbGroupMember tbGroupMember = new TbGroupMember();
        tbGroupMember.setNickname("namesu");
        tbGroupMember.setWxid("wxid_tit3m4v2ftm122");
        tbGroupMember.setAvatar("https://wx.qlogo.cn/mmhead/ver_1/xWnSyhLWbCUNS9WZsCZph0pJcPGEIiaBUZTPuCxEpVJWgr3vVIUOys1dDlZOhXnrrwdja4ZTVicjLsy4licKtZetDqa5by0d0HRr37puWiasIxs/0");
        tbGroupMember.setCommission(0.0D);
        tbGroupMember.setDayCount(0);
        tbGroupMember.setFreezeMoney(0.0D);
        tbGroupMember.setGroupId("43001138253@chatroom");
        tbGroupMember.setIsNotification(1);
        tbGroupMember.setOpenid("test");
        boolean save = tbGroupMemberService.save(tbGroupMember);
        System.out.println("save------->" + save);

        return Result.OK("success！");
    }

    @GetMapping(value = "/isBangding")
    public Result<?> isBangding(){
        TbGroup enableGroupForCell = this.getEnableGroupForCell();
        if(enableGroupForCell==null){
            return Result.error("请登录，再重试!");
        }
        String roomid = enableGroupForCell.getRoomid();
        String name = enableGroupForCell.getDescs();
        Subject currentUser = SecurityUtils.getSubject();
        Object principal = currentUser.getPrincipal();
        LoginUser sysUser = (LoginUser) currentUser.getPrincipal();
        String openid = sysUser.getPassword();
        QueryWrapper<TbGroupMember> tbGroupMemberQueryWrapper = new QueryWrapper<>();
        tbGroupMemberQueryWrapper.lambda().eq(TbGroupMember::getGroupId,roomid).eq(TbGroupMember::getOpenid,openid);
        TbGroupMember one = tbGroupMemberService.getOne(tbGroupMemberQueryWrapper);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("object",one);
        stringObjectHashMap.put("group",roomid);
        stringObjectHashMap.put("groupName",name);
        if(one!=null){
            return Result.OK(stringObjectHashMap);
        }else{
            return Result.error("false");
        }
    }

    @GetMapping(value = "/bangding")
    public Result<?> bangding(@RequestParam(name="key",required=true)String key,@RequestParam(name="code",required=true)String code){
        String lowerCaseCaptcha = code.toLowerCase();
        String realKey = MD5Util.MD5Encode(lowerCaseCaptcha+key, "utf-8");
        System.out.println("realKey1------>"+realKey);
        Object checkCode = redisUtil.get(realKey);
        System.out.println("checkCode------>"+checkCode);

        Result<JSONObject> result = new Result<JSONObject>();
        if(checkCode==null || !checkCode.toString().equals(lowerCaseCaptcha)) {
            result.error500("验证码错误");
            return result;
        }
        System.out.println("正确---------->");
        Subject currentUser = SecurityUtils.getSubject();
        Object principal = currentUser.getPrincipal();
        System.out.println("principal--------->"+principal);
        LoginUser sysUser = (LoginUser) currentUser.getPrincipal();
        String openid = sysUser.getPassword();
        System.out.println("sysUser----->"+sysUser);

        return Result.OK("success！");
    }


    @GetMapping(value = "/getCode")
    public Result<?> getCode(){
        Subject currentUser = SecurityUtils.getSubject();
        Object principal = currentUser.getPrincipal();
        System.out.println("principal--------->"+principal);
        LoginUser sysUser = (LoginUser) currentUser.getPrincipal();
        String openid = sysUser.getPassword();

        String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
        System.out.println("code------->"+code);
        String lowerCaseCode = code.toLowerCase();
        System.out.println(lowerCaseCode);
        //设置5分钟后过期
        redisUtil.set(lowerCaseCode, openid, 60*5);
        Object o = redisUtil.get(lowerCaseCode);
        System.out.println("openid------>"+o);
        return Result.OK(lowerCaseCode);
    }
    @GetMapping(value = "/sendRanmodCode")
    public Result<?> sendRanmodCode(@RequestParam(name="key",required=true)String key){
        Result<String> res = new Result<String>();
        System.out.println("key----->"+key);
        try {
            Subject currentUser = SecurityUtils.getSubject();
            Object principal = currentUser.getPrincipal();
            System.out.println("principal--------->"+principal);
            LoginUser sysUser = (LoginUser) currentUser.getPrincipal();
            String openid = sysUser.getPassword();

            String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
            System.out.println("code------->"+code);
            String lowerCaseCode = code.toLowerCase();
            System.out.println(lowerCaseCode);
            //设置5分钟后过期
            redisUtil.set(lowerCaseCode, openid, 60*5);

            TbGroup enableGroupForCell = this.getEnableGroupForCell();
            if(enableGroupForCell==null){
                res.error500("发送验证码出错，没用可用的群组");
                return res;
            }else{
                this.sendCode(enableGroupForCell.getRoomid(),lowerCaseCode);
                res.setSuccess(true);
                res.setResult("发送成功，验证码5分钟内有效！");
            }
        } catch (Exception e) {
            res.error500("获取验证码出错"+e.getMessage());
            e.printStackTrace();
        }
        return res;
    }


    public TbGroup getEnableGroupForCell(){
        QueryWrapper<TbGroup> tbGroupQueryWrapper = new QueryWrapper<>();
        tbGroupQueryWrapper.lambda().eq(TbGroup::getEnable,TbGroup.ENABLE).eq(TbGroup::getType,TbGroup.CELL);
        TbGroup one = tbGroupService.getOne(tbGroupQueryWrapper);
        if(one!=null){
            return one;
        }else{
            return null;
        }
    }

    public void sendCode(String roomid,String content){
        QueueMessage queueMessage = new QueueMessage();
        queueMessage.setRoomId(roomid);
        queueMessage.setContent(content);
        queueMessage.setRepeat(QueueMessage.is_repeat);
        producer.send(Producer.SERVER_SEND_QUEUE,queueMessage);
        queueMessage.setRepeat(QueueMessage.not_repeat);
        producer.send(Producer.SERVER_SEND_QUEUE,queueMessage);
    }

    @GetMapping(value = "/synchronousGroup")
    public Result<?> synchronousGroup(@RequestParam(name="roomid",required=true) String roomid){
        System.out.println("roomid---------->"+roomid);
        QueueMessage queueMessage = new QueueMessage();
        queueMessage.setRoomId(roomid);
        queueMessage.setRepeat(QueueMessage.is_repeat);
        producer.send(Producer.SERVE_SYNCHRONOUS_GROUP_MSG_QUEUE,queueMessage);

        queueMessage.setRepeat(QueueMessage.not_repeat);
        producer.send(Producer.SERVE_SYNCHRONOUS_GROUP_MSG_QUEUE,queueMessage);

        return Result.OK("请求同步群组成功！");
    }


    @AutoLog(value = "手气最佳")
    @ApiOperation(value="手气最佳", notes="手气最佳")
    @GetMapping(value = "/haveTheBestLuck")
    public Result<?> haveTheBestLuck(@RequestParam(name = "id") String id){
        System.out.println("id------>"+id);
        TbGroupMember tbGroupMember = tbGroupMemberService.getById(id);
        tbGroupMember.setHaveTheBestLuck(new Date());
        boolean b = tbGroupMemberService.updateById(tbGroupMember);
        System.out.println("b---->" + b);
        return Result.OK("处理成功！");
    }

   /**
    * 分页列表查询
    *
    * @param tbGroupMember
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "群成员-分页列表查询")
   @ApiOperation(value="群成员-分页列表查询", notes="群成员-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(TbGroupMember tbGroupMember,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       QueryWrapper<TbGroupMember> queryWrapper = QueryGenerator.initQueryWrapper(tbGroupMember, req.getParameterMap());
       Page<TbGroupMember> page = new Page<TbGroupMember>(pageNo, pageSize);
       IPage<TbGroupMember> pageList = tbGroupMemberService.page(page, queryWrapper);
       return Result.OK(pageList);
   }

   /**
    *   添加
    *
    * @param tbGroupMember
    * @return
    */
   @AutoLog(value = "群成员-添加")
   @ApiOperation(value="群成员-添加", notes="群成员-添加")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody TbGroupMember tbGroupMember) {
       tbGroupMemberService.save(tbGroupMember);
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    *
    * @param tbGroupMember
    * @return
    */
   @AutoLog(value = "群成员-编辑")
   @ApiOperation(value="群成员-编辑", notes="群成员-编辑")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody TbGroupMember tbGroupMember) {
       tbGroupMemberService.updateById(tbGroupMember);
       return Result.OK("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "群成员-通过id删除")
   @ApiOperation(value="群成员-通过id删除", notes="群成员-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       tbGroupMemberService.removeById(id);
       return Result.OK("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "群成员-批量删除")
   @ApiOperation(value="群成员-批量删除", notes="群成员-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.tbGroupMemberService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.OK("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @AutoLog(value = "群成员-通过id查询")
   @ApiOperation(value="群成员-通过id查询", notes="群成员-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       TbGroupMember tbGroupMember = tbGroupMemberService.getById(id);
       if(tbGroupMember==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(tbGroupMember);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param tbGroupMember
   */
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, TbGroupMember tbGroupMember) {
       return super.exportXls(request, tbGroupMember, TbGroupMember.class, "群成员");
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, TbGroupMember.class);
   }

}
